package com.ebt.m.wiki.adapter;

/**
 * Created by Damon.Han on 2017/9/7 0007.
 *
 * @author Damon
 */

import android.content.Context;
import android.graphics.Color;
import android.support.v4.app.FragmentManager;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.ebt.m.R;
import com.ebt.m.adapter.AccordionAdapter;
import com.ebt.m.utils.DataValidation;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.widget.Accordion;
import com.ebt.m.wiki.ExplainWindow;
import com.ebt.m.wiki.bean.BenefitData;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Damon.Han
 * @Description: 手风琴adapter
 * @date 2016年2月3日 上午11:56:45
 */
public class WikiAccordionAdapter extends AccordionAdapter<BenefitData> {
    private List<BenefitData> benefitDatas;
    private Context mContext;
    private Accordion accordionBenefit;
    // 列表展開背景
    private int expandedBackgroundColor = Color.parseColor("#fff7ffee");
    private FragmentManager fragmentManager;

    public WikiAccordionAdapter(FragmentManager fragmentManager, Context context, Accordion accordionBenefit, List<BenefitData> list) {
        super(context, list);
        this.fragmentManager = fragmentManager;
        this.benefitDatas = list;
        this.mContext = context;
        this.accordionBenefit = accordionBenefit;
    }

    @Override
    public View getHeaderView(int position, ViewGroup parent) {
        View headerView = LayoutInflater.from(mContext).inflate(R.layout.wiki_accordation_header, parent, false);
        BenefitData config = benefitDatas.get(position);
        TextView txt_title = (TextView) headerView.findViewById(R.id.title);
        //提取中括号中的内容
        String desc = config.value;
        String REX_ARRAY = "\\[(.*?)\\]";
        Pattern pattern = Pattern.compile(REX_ARRAY);
        Matcher matcher = pattern.matcher(desc);
        String temp = "";
        while (matcher.find()) {
            temp = matcher.group(1);
        }
        String txt = config.title;
        if (!DataValidation.isEmpty(temp)) {
            txt += "：<font color='#D86C00'>" + temp + "</font>";
        }
        txt_title.setText(Html.fromHtml(txt));
        headerView.findViewById(R.id.arrow).setVisibility(DataValidation.isEmpty(config.value.trim()) ? View.GONE : View.VISIBLE);
        return headerView;
    }

    @Override
    public View getContentView(int position, ViewGroup parent) {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.wiki_accordation_content, parent, false);
        return contentView;
    }

    @Override
    public void onExpanded(int position, View headerView) {
        super.onExpanded(position, headerView);
        View contentView = accordionBenefit.getContentView(position);
        BenefitData config = benefitDatas.get(position);
        TextView txt_desc = (TextView) contentView.findViewById(R.id.content);
//        String val = HTMLSpirit.splitAndFilterString(config.value, config.value.length());
        String val = config.value;
        //过滤掉中括号之内的内容1573
        String REX_ARRAY = "\\[(.*?)\\]";
        Pattern pattern = Pattern.compile(REX_ARRAY);
        Matcher matcher = pattern.matcher(val);
        String temp = "";
        while (matcher.find()) {
            temp = matcher.group(0);
            val = val.replace(temp, "");
        }
        txt_desc.setText(getClickableSpan(val));
        //设置超链接可点击
        txt_desc.setMovementMethod(LinkMovementMethod.getInstance());
        ImageView img = (ImageView) headerView.findViewById(R.id.arrow);
        setExpandableStatus(config, headerView, contentView, img, true);
    }

    @Override
    public void onCollapsed(int position, View headerView) {
        super.onCollapsed(position, headerView);
        ImageView img = (ImageView) headerView.findViewById(R.id.arrow);
        BenefitData config = benefitDatas.get(position);
        setExpandableStatus(config, headerView, accordionBenefit.getContentView(position), img, false);
    }

    @Override
    public boolean ifCanExpand(int position) {
        return position >= 0;
    }

    /**
     * 设置列表展开状态
     *
     * @param header
     * @param content
     * @param arrow
     * @param expanded
     */
    private void setExpandableStatus(BenefitData config, View header, View content, ImageView arrow, boolean expanded) {
        if (config.value == null || DataValidation.isEmpty(config.value.trim())) {
            arrow.setVisibility(View.GONE);
            content.setVisibility(View.GONE);
        } else {
            if (expanded) { // 展开
                if (arrow != null) {
                    arrow.setImageResource(R.drawable.icon_arrow_up_green);
                }
                if (header != null) {
                    header.setBackgroundColor(expandedBackgroundColor);
                }
                if (content != null) {
                    content.setBackgroundColor(expandedBackgroundColor);
                }
            } else { // 收回
                if (arrow != null) {
                    arrow.setImageResource(R.drawable.icon_arrow_down_green);
                }
                if (header != null) {
                    header.setBackgroundColor(Color.WHITE);
                }
                if (content != null) {
                    content.setBackgroundColor(Color.WHITE);
                }
            }
        }
    }

    /**
     * 获取可点击的SpannableString
     *
     * @return
     */
    private SpannableString getClickableSpan(String string) {
        String pattern = "<a[^>]*href=(\"([^\"]*)\"|\'([^\']*)\'|([^\\s>]*))[^>]*>(.*?)</a>";
        Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(string);
        HashMap<String, String> map = new HashMap<>();
        while (m.find()) {
            String a = m.group();
            String title = a.substring(a.indexOf(">") + 1, a.indexOf("</a>"));
            string = string.replace(a, title);
            map.put(title, a);
        }
        Iterator iterator = map.entrySet().iterator();
        SpannableString spannableString = new SpannableString(string);
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
            String title = entry.getKey();
            String val = entry.getValue();
            //设置下划线文字
            spannableString.setSpan(new UnderlineSpan(), string.indexOf(title), string.indexOf(title) + title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            //设置文字的前景色
            spannableString.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.common_bg_bar)), string.indexOf(title), string.indexOf(title) + title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            //设置文字的单击事件
            spannableString.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    String url = getUrl(val);
//                    Intent intent = new Intent();
//                    intent.putExtra("title", title);
//                    intent.putExtra("url", url);
//                    intent.setClass(mContext, ExplainWindow.class);
//                    context.startActivity(intent);
                    if (!NetUtils.isNetworkConnected(mContext)) {
                        UIHelper.makeToast(mContext, mContext.getResources().getString(R.string.alert_network));
                        return;
                    }
                    ExplainWindow explainWindow = ExplainWindow.newInstance(title, url);
                    explainWindow.show(fragmentManager, ExplainWindow.class.getName());
                }
            }, string.indexOf(title), string.indexOf(title) + title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableString;
    }


    /**
     * 获取请求url
     *
     * @param a
     */
    private String getUrl(String a) {
        String paraStr = a.substring(a.indexOf("showExplain") + 11, a.indexOf(";"));
        if (paraStr != null && paraStr.length() > 0 && paraStr.contains(",")) {
            paraStr = paraStr.replace("(", "").replace(")", "").replace("'", "");
            String[] argss = paraStr.split(",");
            ArrayList<String> arrayList = new ArrayList(Arrays.asList(argss));
            if (arrayList != null && arrayList.size() == 5) {
                String url = "http://datv2.e-baotong.cn:9089/ashx/getexplain.ashx?brand=" + arrayList.get(2) + "&category=" + arrayList.get(3) + "&item=" + arrayList.get(4);
                return url;
            }
        }
        return null;
    }

}
